
$(function () {
    String.prototype.startWith = function(s) {
        if (s == null || s === "" || this.length === 0 || s.length > this.length)
            return false;
        if (this.substr(0, s.length) === s)
            return true;
        else
            return false;
        return true;
    }

    String.prototype.endWith = function(s) {
        if (s == null || s === "" || this.length === 0|| s.length > this.length)
            return false;
        if (this.substring(this.length - s.length) === s)
            return true;
        else
            return false;
        return true;
    }

    /**
     * Search plugin logic
     * ===================
     */

    var $body = $("body");

    // Search form
    var $form = $('#search-form'),
        $results = $('#search-results'),
        resultsTemplate = Handlebars.compile($('script[type="text/x-handlebars-template"]', $results).html()),
        $phraseInput = $('input[name=phrase]', $form),
        $filterInput = $('input[name=provider]', $form),
        $cachedInput = $('select[name=cached]', $form),
        $resultLimitInput = $('input[name=resultLimit]', $form),
        $progressSpinner = $('.progress .spinner', $form),
        $progressText = $('.progress .text', $form),
        searchXhr = null;

    function search() {
    // if (!$phraseInput.val().length) {
    //     return;
    // }

    if (searchXhr) {
        searchXhr.abort();
    }

    searchXhr = $.ajax({
        url: appRoot + '/route/proc',
        type: 'GET',
        data: $form.serializeArray(),
        beforeSend: function () {
            $results.empty();
            $progressText.text('Please wait...');
            $progressSpinner.removeClass('done');

            if (history.pushState) {
                var formParams = $form.serializeObject();
                var uri = new URI().search(formParams).toString();
                history.pushState({}, document.title, uri)
            }
        },
        complete: function () {
            $progressSpinner.addClass('done');
            $progressText.text('Completed');
        },
        success: function (response) {
            var vars = $.extend({
                url: this.url
            }, response.data);
            console.log(response.data)
            $results.data(vars);
            $results.html(resultsTemplate(vars));
        },
        error: function (xhr) {
            if (xhr.statusText != 'abort') {
                openAlert('Cannot perform search by phrase. Internal server error.');
            }
        }
    });
    }

    var formParams = new URI().search(true);
    populate($form, formParams);

    $phraseInput.on('keyup', _.debounce(search, 1000));
    $filterInput.on('change', search);
    $cachedInput.on('change', search);
    $resultLimitInput.on('change', search);

    //search
    search();

    //upload file
    $("#add-route").bind("click", function () {
        uploadDialog.dialog('open');
        return false;
    });

    var uploadDialogButtons = {};
    uploadDialogButtons["提交"] = function() {
        var file = $(this).find('.multi').val();
        if (file === undefined || file === '') {
            alert('文件未选择.')
            return false;
        }
        if (!file.endWith(".xml")) {
            alert('必须是xml文件.')
            return false
        }
        if (!file.startWith("codyy-route")) {
            alert('文件名必须以codyy-route开头')
            return false
        }
        //$(this).find('form').submit()
    }
    uploadDialog = $('#uploadDialog').dialog({
        autoOpen: false,
        modal   : true,
        width   : '50%',
        buttons : uploadDialogButtons
    });
});


